//
//  WSUserAccount.swift
//  微博
//
//  Created by 武莎莎 on 15/9/7.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import ReactiveCocoa
import AFNetworking


class WSUserAccount: NSObject, NSCoding{
    
    var access_token:String?
    // 基本数据类型必须初始化
    // accessToken的有效期，单位是秒
    var expires_in:NSTimeInterval = 0{
        didSet{
             expireDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // token过期的日期
    var expireDate:NSDate?
    
    // 授权用户的id
    var uid:String?
    var name:String?
    var avatar_large:String?
    
    // MARK: 字典转模型
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // MARK: 重写description属性,没有智能提示
    override var description:String {
        // 注意keys中的值一定要与模型的属性一致，不能有空格
        let keys = ["access_token","expires_in","expireDate","uid","avatar_large","name"]
        // KVC的模型转字典
        return dictionaryWithValuesForKeys(keys).description
    }
    
    static let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("wsAccount.plist")
    
    // MARK: 归档用户信息
    func saveUserAccount(){
        // 拼接保存的路径字符串
        // 调用全局属性：类名.属性
        print(WSUserAccount.path)
        // 键值归档
        NSKeyedArchiver.archiveRootObject(self, toFile: WSUserAccount.path)
    }
    
    // MARK: 解档用户信息
    private static var userAccount:WSUserAccount?
    class func loadUserAccount()->WSUserAccount?{
        if userAccount == nil{
            print(path)
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? WSUserAccount
        }
        if let date = userAccount?.expireDate where date.compare(NSDate()) != NSComparisonResult.OrderedDescending{
            userAccount = nil
        }
        // 类函数可以直接获取到static的属性
        return userAccount
    }
    // MARK:归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expireDate, forKey: "expireDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    // MARK:解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expireDate = aDecoder.decodeObjectForKey("expireDate") as? NSDate
    }
}
